<?php

namespace Home\Controller;

/**
 * 长租房ajax接口
 * @modify zhangzhen 2017-07-27 创建
 */
class LongRoomController extends ParentController {
    protected $hotelId;

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $this->hotelId = I('post.hotel');
        $adminAuthorityLogic->check($this->hotelId);
    }

    /**
     * 获取房型与房间
     * @add zhangzhen 2017-3-24 创建
     */
    public function getRoomList() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        // TOOD:添加权限校验,暂时只有超级管理员可以访问
        
        $roomLogic = A('Common/Room', 'Logic');
        $returnData = $roomLogic->getLongRoomList($this->hotelId);
        returnJson(200, 200, $returnData);
    }

    /**
     * 获取长租房
     * @add zhangzhen 2017-3-27 创建
     */
    public function getLongRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotelId = $param['hotel'];
        $longRoomLogic = A('Common/LongRoom', 'Logic');
        $longRoomInfos = $longRoomLogic->getInfosByHotel($hotelId);
        returnJson(200, 200, $longRoomInfos);
    }

     /**
     * 添加长租房
     * @add zhangzhen 2017-7-27 创建
     */
    public function addLongRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'price' => 'notnull,notempty,gtZero,decimal8_2',
            'roomInfoIds' => 'notnull,notempty',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $price = $param['price'];
        $roomInfoIds = $param['roomInfoIds'];
        $roomTypeId = $param['roomTypeId'];
        $userId = getUserId();
        $dataList = [];
        foreach ($roomInfoIds as $key => $roomInfoId) {
            $dataList[$key]['hotelentity_id'] = $hotel;
            $dataList[$key]['roominfo_id'] = $roomInfoId;
            $dataList[$key]['roomtype_id'] = $roomTypeId;
            $dataList[$key]['creator'] = $userId;
            $dataList[$key]['operator'] = $userId;
        }
        unset($roomInfoId);
        $longRoomModel = D('LongRoom');
        $longRoomModel->startTrans();
        $commit = true;
        $result = $longRoomModel->addAllInfos($dataList);
        if ($result === false) {
            $commit = false;
        }

        if ($commit === true) {
            $roomTypeModel = D('RoomType');
            $result = $roomTypeModel->saveLongRoomPrice($roomTypeId, $price);
            if ($result === false) {
                $commit = false;
            }
        }

        if ($commit === false) {
            $longRoomModel->rollback();
            returnJson(500, 508);
        } else {
            $longRoomModel->commit();
            $longRoomLogic = A('Common/LongRoom', 'Logic');
            $longRoomInfos = $longRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $longRoomInfos);
        }
    }

    /**
     * 获取长租房
     * @add zhangzhen 2017-5-15 创建
     */
    public function getRoomByTypeId() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $roomTypeId = $param['roomTypeId'];
        $roomInfoModel = D('RoomInfo');
        $roomInfos = $roomInfoModel->getRoomByTypeId($roomTypeId);
        $roomTypeModel = D('RoomType');
        $longPrice = $roomTypeModel->getLongPrice($roomTypeId);
        returnJson(200, 200, ['roomInfos' => $roomInfos, 'longPrice' => $longPrice['longprice']]);
    }

    /**
     * 修改长租房
     * @add zhangzhen 2017-7-27 创建
     */
    public function saveLongRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'waitForDelete' => 'notempty',
            'waitForAdd' => 'notempty',
            'roomTypeId' => 'notnull,notempty,id',
            'price' => 'notnull,notempty,gtZero,decimal8_2',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $roomTypeId = $param['roomTypeId'];
        $price = $param['price'];
        $userId = getUserId();

        // 获取客栈默认符号
        $symbol = $this->getDefultCurrencyByHotel($hotel);

        $roomTypeModel = D('RoomType');
        $roomTypeModel->startTrans();
        $commit = true;
        $priceLogMap = array(
            'zh_cn' => '价格设置为' . $symbol,
            'en_us' => 'set price ' . $symbol,
            'zh_tw' => '價格設置为' . $symbol,
        );
        $roomTypeInfo = $roomTypeModel->getLongPrice($roomTypeId);
        if ($roomTypeInfo['longprice'] != $price) {
            $result = $roomTypeModel->saveLongRoomPrice($roomTypeId, $price);
            if ($result === false) {
                $commit = false;
            } else {
                priceChangeLog($hotel, $roomTypeId, $priceLogMap[LANG_SET] . $price, strtotime(date('Y-m-d')), '', LONG_PRICE, '');
            }
        }
        
        if ($commit === true) {
            $longRoomModel = D('LongRoom');
            if(isset($param['waitForDelete'],$param['waitForAdd'])){
                $waitForDelete = $param['waitForDelete'];
                $waitForAdd = $param['waitForAdd'];
                $tempAdd = array_diff($waitForAdd,$waitForDelete);
                $waitForDelete = array_diff($waitForDelete,$waitForAdd);
                $waitForAdd = $tempAdd;
            }

            if (isset($param['waitForDelete'])) {
                $waitForDelete = isset($waitForDelete) ? $waitForDelete : $param['waitForDelete'];
                $waitForDelete = implode(',', $waitForDelete);
                $orderRoomModel = D('OrderRoom');
                // 检查房间是否有活跃状态订单
                $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotel, $waitForDelete);
                // 无效订单无法阻止房间删除
                foreach ($orderInfo as $index => $orderItem) {
                    if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED)) || $orderItem['night'] <= 7) {
                        unset($orderInfo[$index]);
                    }
                }
                unset($orderItem);
                if(!empty($orderInfo)) {
                    $roomTypeModel->rollback();
                    returnJson(403, 300, 'error');
                }
                $longRoomModel->deleteInfosInIds($waitForDelete);
            }

            if (isset($param['waitForAdd'])) {
                $waitForAdd = isset($waitForAdd) ? array_values($waitForAdd) : array_values($param['waitForAdd']);
                $dataList = [];
                foreach ($waitForAdd as $key => $roomInfoId) {
                    $dataList[$key]['hotelentity_id'] = $hotel;
                    $dataList[$key]['roominfo_id'] = $roomInfoId;
                    $dataList[$key]['roomtype_id'] = $roomTypeId;
                    $dataList[$key]['creator'] = $userId;
                    $dataList[$key]['operator'] = $userId;
                }
                $result = $longRoomModel->addAllInfos($dataList);
                if ($result === false) {
                    $commit = false;
                }
            }
        }
        if ($commit === false) {
            $roomTypeModel->rollback();
            returnJson(500, 508);
        } else {
            $roomTypeModel->commit();
            $longRoomLogic = A('Common/LongRoom', 'Logic');
            $longRoomInfos = $longRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $longRoomInfos);
        }
    }

    /**
     * 删除长租房
     * @add zhangzhen 2017-7-27 创建
     */
    public function deleteLongRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $roomTypeId = $param['roomTypeId'];

        $longRoomModel = D('LongRoom');
        $longRoomInfos = $longRoomModel->getInfosByRoomType($roomTypeId);
        $roomIds = array_column($longRoomInfos, 'roominfo_id');

        $orderRoomModel = D('OrderRoom');
        // 检查房间是否有活跃状态订单
        $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotel, $roomIds);
        // 无效订单无法阻止房间删除
        foreach ($orderInfo as $index => $orderItem) {
            if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED)) || $orderItem['night'] <= 7) {
                unset($orderInfo[$index]);
            }
        }
        unset($orderItem);
        if(!empty($orderInfo)) {
            returnJson(403, 300, 'error');
        }
        $longRoomModel->startTrans();
        $commit = true;
        $result = $longRoomModel->deleteInfoByTypeId($roomTypeId);
        if (! $result) {
            $commit = false;
        }
        if ($commit) {
            $roomTypeModel = D('RoomType');
            $result = $roomTypeModel->saveLongRoomPrice($roomTypeId, '0.00');
            if (! $result) {
                $commit = false;
            }
        }
        if ($commit) {
            $longRoomModel->commit();
            $longRoomLogic = A('Common/LongRoom', 'Logic');
            $longRoomInfos = $longRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $longRoomInfos);
        } else {
            $longRoomModel->rollback();
            returnJson(500, 510);
        }
    }

}
